package com.neuedu.helloworld;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;


/**
 * com.neuedu.helloworld.R
 */
public class LoginActivitybak extends AppCompatActivity implements View.OnClickListener {


    public static final String AUTO_LOGIN = "login";

    private Button btnLogin;
    private TextView txtForgetPassword;
    private EditText etUserName;
    private EditText etPassword;
    private CheckBox ckRemember;


    //定义在主线程的
//    Handler handler = new Handler(){
    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {


//            msg.arg1;
//            msg.arg2;
//            msg.what;

//            msg.obj


            if(msg.what == 1 ){

                if(msg.arg1 == 1){ //登录成功
                    //此处更新UI线程

                    String token = (String) msg.obj;

                    //token  -- ShareadPreferences

                    //显示意图
                    Intent intent = new Intent(LoginActivitybak.this, MainActivity.class );

                    //通过意图启动Activity
                    startActivity(intent);

                    //结束当前的Activity 新画面 后退的时候看不到这个LoginActivity
                    finish();

                }else if (msg.arg1 == 2){
                    String errorMSG = "用户名或密码不正确"; //(String) msg.obj;
                    Toast.makeText(LoginActivitybak.this, errorMSG, Toast.LENGTH_SHORT).show();
                }



            }else{ //请求你失败了， 404  没有全新啊
                Toast.makeText(LoginActivitybak.this, "网络请求失败,请联系管理员", Toast.LENGTH_SHORT).show();
            }

        }
    };











    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //R   android.R
        setContentView(R.layout.activity_login);

        //加载完布局文件，当前Activity可以获取到组件
        btnLogin = findViewById(R.id.btnLogin);
        txtForgetPassword = findViewById(R.id.txtForgetPassword);
        etUserName = findViewById(R.id.etUserName);
        etPassword = findViewById(R.id.etPassword);
        ckRemember = findViewById(R.id.ckRemember);


        txtForgetPassword.setText(Html.fromHtml("<a href=\"http://www.12306.cn/lostPassword\">忘记密码？</a>"));
        txtForgetPassword.setMovementMethod(LinkMovementMethod.getInstance());


        //设置事件监听对象
//        btnToMain.setOnClickListener(new BtnClickListener());
        btnLogin.setOnClickListener(this);

        System.out.println("日志日志日志日志日志1");


        Log.i("LoginActivity", "i一般信息");
        Log.v("LoginActivity", "v冗余");
        Log.w("LoginActivity", "w警告");
        Log.e("LoginActivity", "e错误异常的");

        Log.d("LoginActivity", " LoginActivity.onCreate ");

    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.d("LoginActivity", ":  LoginActivity.onStart ");


    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("LoginActivity", ":  LoginActivity.onResume ");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("LoginActivity", ":  LoginActivity.onPause ");


    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.d("LoginActivity", ":  LoginActivity.onStop ");

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("LoginActivity", ":  LoginActivity.onDestroy ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("LoginActivity", ":  LoginActivity.onRestart ");
    }


    @Override
    public void onClick(View v) {
        //吐司
        //Toast.makeText(this, "按钮被点击.....", Toast.LENGTH_LONG).show();


        //访问  用户名、密码的文本框
        String userName = etUserName.getText().toString();
        String password = etPassword.getText().toString();


        if (userName == null || userName.trim().length() <= 0) {
            etUserName.requestFocus();
            etUserName.setError("请输入用户名");
            return;
        }

        if (password == null || password.trim().length() <= 0) {
            etPassword.requestFocus();
            etPassword.setError("请输入密码");
            return;
        }


        new LoginTread(userName,password).start();


//        //登录成功的时候
//        if("admin".equals(userName) && "123456".equals(password)){
//
//
//            autoLogin();
//
//
//            //跳转到新 的activity
//            //显示意图
//            Intent intent = new Intent(this, MainActivity.class );
//
//            //通过意图启动Activity
//            startActivity(intent);
//
//            //结束当前的Activity 新画面 后退的时候看不到这个LoginActivity
//            finish();
//        }else{
//            etUserName.setError("用户名或者密码不对");
//        }


    }

    //判断是否自动登录， 如果勾选了，需要记录  username、password
    private void autoLogin() {
        if (ckRemember.isChecked()) {
            String userName = etUserName.getText().toString();
            String password = etPassword.getText().toString();


            //通过 SharedPreferences 记录用户名密码（token）

            //创建一个SharedPreferences 对象(xxx.xml)
            SharedPreferences sharedPreferences = getSharedPreferences(LoginActivitybak.AUTO_LOGIN, MODE_PRIVATE);


            //写入
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("username", userName);
            edit.putString("password", password);


            //commit
            edit.commit();

        }


    }


    //定义监听器
//    class BtnClickListener implements  View.OnClickListener{
//
//        @Override
//        public void onClick(View v) {
//
//            Toast.makeText(LoginActivity.this, "按钮被点击.....", Toast.LENGTH_LONG).show();
//
//
//        }
//    }


    class LoginTread extends Thread {

        String username ;
        String password ;

        public LoginTread(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        public void run() {



            Message msg = handler.obtainMessage();




            try {
                URL url = new URL("http://192.168.77.11:8080/login?username="+username+"&password="+password);
                URLConnection connection = url.openConnection();




                InputStream inputStream = connection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

//                StringBuffer sb = new StringBuffer();
//                char[] chars = new char[1024];
//                int len = -1;
//                while ((len = br.read(chars)) != -1) {
//                    sb.append(chars, 0, len);
//                }



//                String json  =  sb.toString();
                //xml  json

                Gson gson = new GsonBuilder().create();
                HashMap map = gson.fromJson(br, HashMap.class);


                Double  code = (Double) map.get("code");


                msg.what = 1; //网络请求成功了


                if(code.intValue() == 200){
                    String token  = (String) map.get("token");
                    Log.d("NETWORK","token: "+token);
                    //跳转到新 的activity

                     //10秒

                    msg.arg1 = 1;
                    msg.obj = token;

                }else{
                    msg.arg1 = 2;
//                    String errorMsg  = (String) map.get("errorMsg");
//                    msg.obj = errorMsg;
                    Log.d("NETWORK","登录失败了");

                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                msg.what = 2; //网络请求失败了
            } catch (IOException e) {
                e.printStackTrace();
                msg.what = 2; //网络请求失败了
            }
            handler.sendMessage(msg);

        }
    }


}